module OrganizationRepository

  def find_requre_certificate_organ_by_organ organ_id
    organ = Organization.find(organ_id)
    Organization.find_parent(organ_id).push(organ).inject([]){|r, e| r + Organization.position_standard_assignments(e["id"]).map(&:requre_certificate_organ) }.uniq
  end

  def update_requre_certificate_organ organization, requre_certificate_organs
    old_requre_certificate_organs    = find_requre_certificate_organ_by_organ(organization.id).map(&:name)
    remove_requre_certificate_organs = old_requre_certificate_organs - requre_certificate_organs
    add_requre_certificate_organs    = requre_certificate_organs     - old_requre_certificate_organs

    organization.position_standard_assignments.where(requre_certificate_organ: remove_requre_certificate_organs).map { |e| e.delete }

    add_requre_certificate_organs.each do |requre_certificate_organ|
      position_standard_assignment = PositionStandardAssignment.new(organization_id: organization.id)
      position_standard_assignment.requre_certificate_organ =  RequireCertificateOrgan.find_by_name(requre_certificate_organ)
      position_standard_assignment.save!
    end
  end
end
